package com.diver.flinkdemo.service.impl;


import com.diver.flinkdemo.dto.xxt.C40DataVO;
import com.diver.flinkdemo.entity.xxt.SmsCollection;
import com.diver.flinkdemo.mapper.mysqlMapper.SmsCollectionMapper;
import com.diver.flinkdemo.service.ISmsCollectionService;
import com.diver.flinkdemo.utils.DateUtil;
import com.diver.flinkdemo.utils.DynamicDataSourceUtil;
import com.diver.flinkdemo.utils.UUIDUtil;
import com.diver.flinkdemo.utils.UnicodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hesc
 * @since 2022-03-02
 */
@Slf4j
public class SmsCollectionServiceImpl implements ISmsCollectionService {
    private SmsCollectionMapper mapper;
    private SqlSession session;

    @Override
    public List<SmsCollection> getSmsCollectionList(String imei, Integer limit) {
        try {
            session = DynamicDataSourceUtil.mysqlSessionFactory.openSession();
            mapper = session.getMapper(SmsCollectionMapper.class);
            return mapper.getSmsCollectionList(imei, limit);
        } finally {
            endOfSession(session);
        }
    }

    @Override
    public void addSmsCollection(C40DataVO c40DataVO) {

        try {
            session = DynamicDataSourceUtil.mysqlSessionFactory.openSession(true);
            mapper = session.getMapper(SmsCollectionMapper.class);
            String imei = c40DataVO.getImei();
            log.info("短信代收回调，数据:{}", c40DataVO);
            if(StringUtils.isEmpty(imei)) {
                return;
            }
            SmsCollection smsCollection = new SmsCollection();
            smsCollection.setMsgId(c40DataVO.getMsgId());
            smsCollection.setDeviceId(imei);
            String phone = c40DataVO.getOtherCallNum();
            if(StringUtils.isNotBlank(phone)) {
                phone = phone.replaceAll("\\+86", "");
            }
            smsCollection.setOtherCallNum(phone);
            if(StringUtils.isNotBlank(c40DataVO.getReceivedTime())) {
                smsCollection.setReceivedTime(c40DataVO.getReceivedTime().substring(0, 10) + " " + c40DataVO.getReceivedTime().substring(c40DataVO.getReceivedTime().length()-8, c40DataVO.getReceivedTime().length()));
            } else {
                smsCollection.setReceivedTime(DateUtil.getNowDateString());
            }
            String msgContent = c40DataVO.getShortMsg();
            smsCollection.setShortMsg(msgContent);
            smsCollection.setCreateTime(System.currentTimeMillis());
            smsCollection.setSmsStatus(0);
            mapper.insert(smsCollection);
        } finally {
            endOfSession(session);
        }
    }

    public void endOfSession(SqlSession session) {
        //关闭sqlSession
        if (session != null) {
            log.info("session commit -> session close");
//            session.commit();
            session.close();
        }
    }
}
